package com.oauth2.demo2.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @ClassName UserContoller
 * @Description 测试类
 * @Author Liujt
 * @Date 2020/1/15 14:23
 **/
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @GetMapping("/me")
    public Object getCurrentUser(Authentication user, HttpServletRequest request) throws UnsupportedEncodingException {
        String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header,"bearer ");

        //从JWT中解析信息
        Claims claims = Jwts.parser()
                .setSigningKey("SigningKey".getBytes("UTF-8"))
                .parseClaimsJws(token)
                .getBody();

        return user;
    }

    @PostMapping("/me")
    public Object postCurrentUser(@AuthenticationPrincipal UserDetails user) {
        return user;
    }
}
